package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.PointCheckTask;
import com.ruoyi.system.domain.ValidationGroups.*;
import com.ruoyi.system.domain.vo.CreateTaskGatherVO;
import com.ruoyi.system.domain.vo.DeviceHistoryDto;
import com.ruoyi.system.domain.vo.PointCheckPCReportVO;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IPointCheckTaskService;
import com.ruoyi.system.service.IProjectAuthorizeService;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/system/point_check_task")
public class PointCheckTaskController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IPointCheckTaskService pointCheckTaskService;
    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;

    /**
     * 点检任务分页查询（PC）
     *
     * @param pointCheckTask
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(PointCheckTask pointCheckTask) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        if (flag){
            Long customerId = sysDeptService.getCustomerId(loginUser.getUser().getDeptId());
            if (pointCheckTask.getDeptId() != null){
                if (customerId.compareTo(pointCheckTask.getDeptId()) != 0){
                    customerId = pointCheckTask.getDeptId();
                }
            }
            pointCheckTask.setDeptId(customerId);
        }
        if (StrUtil.isNotBlank(pointCheckTask.getStatus())) {
            pointCheckTask.setStatusList(StrUtil.splitTrim(pointCheckTask.getStatus(), ","));
        }
        startPage();
        pointCheckTask.setCompanyId(companyId);
        List<PointCheckTask> pointCheckTasks = pointCheckTaskService.queryList(pointCheckTask);
        //客户公司下面过滤项目合同号
        if (flag && CollUtil.isNotEmpty(pointCheckTasks)){
            pointCheckTasks.forEach(a ->{
                a.setProjectCode(null);
            });
        }
        return getDataTable(pointCheckTasks);
    }

    /**
     * 点检任务分页查询（APP）
     *
     * @param pointCheckTask
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:task:app:list')")
    @GetMapping("/app/list")
    public TableDataInfo appList(PointCheckTask pointCheckTask) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String userName = loginUser.getUser().getUserName();
        pointCheckTask.setExecutor(userName);
        pointCheckTask.setCompanyId(companyId);
        if (StrUtil.isNotBlank(pointCheckTask.getStatus())) {
            pointCheckTask.setStatusList(StrUtil.splitTrim(pointCheckTask.getStatus(), ","));
        }
        startPage();
        List<PointCheckTask> pointCheckTasks = pointCheckTaskService.queryList(pointCheckTask);
        boolean flag = sysDeptService.checkIsCustomer(loginUser.getUser().getDeptId());
        //客户公司下面过滤项目合同号
        if (flag && CollUtil.isNotEmpty(pointCheckTasks)){
            pointCheckTasks.forEach(a ->{
                a.setProjectCode(null);
            });
        }
        return getDataTable(pointCheckTasks);
    }

    @PreAuthorize("@ss.hasPermi('system:point:check:task:app:list')")
    @GetMapping("/app/list_progress")
    public AjaxResult appListProgress(PointCheckTask pointCheckTask) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String userName = loginUser.getUser().getUserName();
        pointCheckTask.setExecutor(userName);
        pointCheckTask.setCompanyId(companyId);
        List<PointCheckTask> pointCheckTasks = pointCheckTaskService.queryListProgress(pointCheckTask);
        return AjaxResult.success(pointCheckTasks);
    }

//    /**
//     * 点检任务编辑
//     *
//     * @param pointCheckTask
//     * @return
//     */
//    @PreAuthorize("@ss.hasPermi('system:point:check:task:edit')")
//    @PostMapping("/edit")
//    public AjaxResult edit(@RequestBody @Validated(Update.class) PointCheckTask pointCheckTask) {
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        projectAuthorizeService.checkPointCheckTaskOperationStatus(user,pointCheckTask.getId());
//        checkTaskDate(pointCheckTask);
//        pointCheckTaskService.checkExecutorStatus(pointCheckTask);
//        if (pointCheckTaskService.update(pointCheckTask)) {
//            return AjaxResult.success("修改成功");
//        }
//        return AjaxResult.error("修改失败");
//    }

    @PreAuthorize("@ss.hasPermi('system:point:check:task:add')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated(Create.class) PointCheckTask pointCheckTask) {
        checkTaskDate(pointCheckTask);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        pointCheckTask.setCompanyId(companyId);
        pointCheckTask.setCreateTime(new Date());
        pointCheckTask.setCreateBy(loginUser.getUsername());
        pointCheckTask.setStatus("0");
        //验证指派人状态
        pointCheckTaskService.checkExecutorStatus(pointCheckTask);
        if (pointCheckTaskService.add(pointCheckTask)) {
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    @PreAuthorize("@ss.hasPermi('system:point:check:task:add')")
    @PostMapping("/add_v2")
    public AjaxResult addV2(@RequestBody @Validated(Create.class) PointCheckTask pointCheckTask) {
        checkTaskDate(pointCheckTask);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        pointCheckTask.setCompanyId(companyId);
        pointCheckTask.setCreateTime(new Date());
        pointCheckTask.setCreateBy(loginUser.getUsername());
        pointCheckTask.setCategory(1);
        pointCheckTask.setStatus("0");
        //验证指派人状态
        pointCheckTaskService.checkExecutorStatus(pointCheckTask);
        if (pointCheckTaskService.addV2(pointCheckTask)) {

            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    /**
     * 创建任务汇总
     *
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:task:app:list')")
    @GetMapping("/create_task_gather")
    public AjaxResult createTaskGather(Integer id) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        queryVo.filters.put("companyId", companyId);
        CreateTaskGatherVO taskGather = pointCheckTaskService.getTaskGather(queryVo);
        return AjaxResult.success(taskGather);
    }

    /**
     * 获取产品点检异常历史
     *
     * @param sn
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:point:check:task:get_device_history')")
    @GetMapping("/get_device_history")
    public AjaxResult getDeviceHistory(String sn) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("sn",sn);
        queryVo.filters.put("dept_id", loginUser.getUser().getDeptId());
        queryVo.filters.put("company_id", sysDeptService.selectCompanyIdByUser(loginUser.getUser()));
        List<DeviceHistoryDto> result = pointCheckTaskService.getDeviceHistory(queryVo);
        return AjaxResult.success(result);
    }

    /**
     * 校验任务时间
     *
     * @param pointCheckTask
     */
    private void checkTaskDate(PointCheckTask pointCheckTask) {
        //获取开始时间的当天开始时间
        DateTime beginOfDay = DateUtil.beginOfDay(pointCheckTask.getStartTime());
        //获取开始时间的当天开始时间
        DateTime endOfDay = DateUtil.endOfDay(pointCheckTask.getStartTime());
        if (pointCheckTask.getStartTime().compareTo(pointCheckTask.getEndTime()) >= 0) {
            throw new CustomException("开始时间不能大于或等于结束时间");
        }
        if (endOfDay.compareTo(pointCheckTask.getEndTime()) < 0) {
            throw new CustomException("开始时间与结束时间不能跨天");
        }
    }

    @PreAuthorize("@ss.hasPermi('system:point:check:task:add')")
    @GetMapping("/get_device_enum")
    public TableDataInfo getDeviceEnum(Integer projectId,Integer groupId){
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("project_id",projectId);
        queryVo.filters.put("group_id",groupId);
        startPage();
        List<Map<String, Object>> deviceEnum = pointCheckTaskService.getDeviceEnum(queryVo);
        return getDataTable(deviceEnum);
    }
}
